#!/bin/bash

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
WHITE='\033[1;37m'
NC='\033[0m' # No Color

# 彩色输出函数
info() { echo -e "${WHITE}[信息]${NC} $1"; }
warn() { echo -e "${YELLOW}[警告]${NC} $1"; }
error() { echo -e "${RED}[错误]${NC} $1"; exit 1; }
title() { echo -e "${BLUE}$1${NC}"; }

# 作者信息
AUTHOR_REPO="https://gitee.com/cncsrf"
PROJECT_REPO="https://gitee.com/cncsrf/rsync-realtime-dir-sync"

# 欢迎信息
title "================================================"
title "  Rsync本机目录实时备份同步一键脚本"
title "================================================"
info " 功能说明:"
info " 1. 自动安装必要软件(rsync/inotify-tools)"
info " 2. 配置源目录和目标目录"
info " 3. 创建系统服务实现开机自启"
info " 4. 实时监控并同步目录变化"
info " 5. 提供完整的日志记录功能"
info ""
info " 支持系统: Debian12 / Ubuntu22.04 / CentOS7"
warn " 注意: 其它系统未经测试，可能不兼容"
info ""
info " 项目仓库地址: ${PROJECT_REPO}"
warn ""
warn " 操作前请确保:"
warn " 1. 您有root权限"
warn " 2. 网络连接正常"
warn " 3. 磁盘空间充足"
title "================================================"

# 日志记录
log() { info "[$(date '+%Y-%m-%d %H:%M:%S')] $1"; }

# 检查root权限
[ "$(id -u)" != "0" ] && error "此脚本需要root权限执行!"

# 确认继续
read -p "$(info '是否继续安装? (y/n) ')" -n 1 -r
echo
[[ ! $REPLY =~ ^[Yy]$ ]] && exit 0

# 检测系统类型
detect_os() {
    if [ -f /etc/redhat-release ]; then
        echo "centos"
    elif grep -qi "debian" /etc/os-release; then
        echo "debian"
    elif grep -qi "ubuntu" /etc/os-release; then
        echo "ubuntu"
    else
        echo "unknown"
    fi
}

OS_TYPE=$(detect_os)

# 安装必要软件
log "正在安装必要软件..."
case $OS_TYPE in
    centos)
        yum install -y epel-release
        yum install -y rsync inotify-tools at
        ;;
    debian|ubuntu)
        apt-get update
        apt-get install -y rsync inotify-tools at
        ;;
    *)
        error "不支持的操作系统!"
        ;;
esac
[ $? -ne 0 ] && error "软件安装失败!"
log "软件安装成功!"

# 配置目录
warn "请输入源目录路径(默认:/opt/source): "
read WATCH_DIR
WATCH_DIR=${WATCH_DIR:-/opt/source}
WATCH_DIR=${WATCH_DIR%/}/

warn "请输入目标目录路径(默认:/opt/target): "
read SYNC_DEST
SYNC_DEST=${SYNC_DEST:-/opt/target}
SYNC_DEST=${SYNC_DEST%/}/

warn "请输入同步延迟时间(秒，默认:5): "
read DELAY
DELAY=${DELAY:-5}

# 创建目录
log "正在创建目录..."
mkdir -p "$WATCH_DIR" || error "无法创建源目录!"
mkdir -p "$SYNC_DEST" || error "无法创建目标目录!"
log "目录创建成功:"
info "源目录: $WATCH_DIR"
info "目标目录: $SYNC_DEST"
info "同步延迟: ${DELAY}秒"

# 创建同步脚本
log "正在创建同步脚本..."
SYNC_SCRIPT="/usr/local/bin/rsync-realtime-dir-sync.sh"
LOG_FILE="/var/log/rsync-realtime-dir-sync.log"

cat > "$SYNC_SCRIPT" <<EOF
#!/bin/bash

WATCH_DIR="$WATCH_DIR"
SYNC_DEST="$SYNC_DEST"
DELAY=$DELAY
LOG_FILE="$LOG_FILE"

# 确保日志目录存在
mkdir -p "\$(dirname "\$LOG_FILE")"
touch "\$LOG_FILE"

echo "\$(date '+%Y-%m-%d %H:%M:%S') 开始监控目录 \$WATCH_DIR 的变化..." | tee -a "\$LOG_FILE"

while inotifywait -r -e modify,create,delete,move --format '%w%f' "\$WATCH_DIR"; do
    echo "\$(date '+%Y-%m-%d %H:%M:%S') 检测到 \$WATCH_DIR 中的变化。将在 \$DELAY 秒后执行同步..." | tee -a "\$LOG_FILE"
    
    sleep \$DELAY
    
    echo "\$(date '+%Y-%m-%d %H:%M:%S') 正在执行同步..." | tee -a "\$LOG_FILE"
    # 关键修改：正确同步目录结构
    rsync -av --delete "\$WATCH_DIR." "\$SYNC_DEST" >> "\$LOG_FILE" 2>&1
    
    if [ \$? -eq 0 ]; then
        echo "\$(date '+%Y-%m-%d %H:%M:%S') 同步成功完成" | tee -a "\$LOG_FILE"
    else
        echo "\$(date '+%Y-%m-%d %H:%M:%S') 同步失败，请检查日志" | tee -a "\$LOG_FILE"
    fi
done
EOF

chmod +x "$SYNC_SCRIPT"
log "同步脚本创建成功: ${SYNC_SCRIPT}"

# 创建系统服务
log "正在创建系统服务..."
SERVICE_FILE="/etc/systemd/system/rsync-realtime-dir-sync.service"

cat > "$SERVICE_FILE" <<EOF
[Unit]
Description=Rsync Realtime Directory Sync Service
After=network.target

[Service]
Type=simple
ExecStart=$SYNC_SCRIPT
Restart=always
RestartSec=5
User=root

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl enable rsync-realtime-dir-sync
systemctl start rsync-realtime-dir-sync

if systemctl is-active --quiet rsync-realtime-dir-sync; then
    log "服务启动成功!"
    info "服务状态: $(systemctl is-active rsync-realtime-dir-sync)"
else
    error "服务启动失败!"
    journalctl -u rsync-realtime-dir-sync -n 10 --no-pager
fi

# 完成信息
title "================================================"
title "  目录同步服务配置完成!"
info " 源目录: $WATCH_DIR"
info " 目标目录: $SYNC_DEST"
info " 同步延迟: ${DELAY}秒"
info " 同步脚本: $SYNC_SCRIPT"
info " 日志文件: $LOG_FILE"
info ""
info " 常用命令:"
info " - 启动服务: systemctl start rsync-realtime-dir-sync"
info " - 停止服务: systemctl stop rsync-realtime-dir-sync"
info " - 查看状态: systemctl status rsync-realtime-dir-sync"
info " - 查看日志: journalctl -u rsync-realtime-dir-sync -f"
info " - 实时日志: tail -f $LOG_FILE"
info ""
info " 更多信息请访问项目仓库: ${PROJECT_REPO}"
title "================================================"